package com.yumei.trader.gym.act;

import android.content.Context;


import com.yumei.trader.gym.view.element.TicketElement;

import java.io.Serializable;
import java.util.ArrayList;

public abstract class TraderAct extends BaseAct implements Serializable {

    private float cost; //成本价

    private float rise; //收益

    private double count;  //持股

    private double value; //市值

    private double profit; //收益额

    private boolean buyIn = false;

    private int actionType = 0;

    //交易记录
    private ArrayList<BSAction> bsArr = new ArrayList<>();
    private BSAction bsEl;

    public TraderAct(Context context){
        super(context);
    }


    public float getCost(){
        return cost;
    }

    public float getRise(){
        return rise;
    }

    public double getCount(){
        return count;
    }

    public double getValue(){
        return value+getCashValue();
    }

    public boolean isBuyIn(){
        return buyIn;
    }

    public int getTraderTimes(){
        return bsArr.size();
    }

    public ArrayList<BSAction> getBsArr(){
        return bsArr;
    }

    public void reset(){
        super.reset();
        bsArr.clear();
        clear();
    }

    public void clear(){
        value = 0;
        cost = 0;
        rise = 0;
        count = 0;
        buyIn = false;
    }


    public boolean onBuyAction(TicketElement el, int index, int status){

        actionType = status;

        count = ((long)(getCashValue()/el.close/100))*100;
        if(count > 0){

            /*if(count > 1000*100){ //超过1000手
                count = 1000*100;
                System.out.println(" ================ count ="+count);
            }*/

            value = count * el.close;
            cost = el.close;
            turnOutValue(value);
            buyIn = true;
            el.flag = 1;

            bsEl = new BSAction(index);
            bsEl.buyPrice = cost;
            bsEl.count = (int)count;
            bsEl.actionType = (actionType == 0 ? "Long" : "Short");
            el.type = bsEl.actionType;
            return true;
        }
        return false;
    }

    public boolean onSellAction(TicketElement el, int index){

        turnInValue(value);
        bsEl.sellPrice = el.close;
        clear();
        el.flag = -1;
        el.type = bsEl.actionType;
        bsArr.add(bsEl.sellIndex(index));

        return true;
    }

    public void onUpdateAction(TicketElement el){

        if(buyIn) {
            if (actionType == 0){
                value = count * el.close;
                rise = (el.close - cost) * 100 / cost;
                profit = (el.close - cost) * count;
            }else {
                value = count * cost + (-(el.close - cost) * count);
                rise = -(el.close - cost) * 100 / cost;
                profit = -(el.close - cost) * count;
            }
            saveCashAccount();
        }
    }

    public double getProfit() {
        return profit;
    }
}
